#include <wiringPi.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>

#ifdef __cplusplus
#include <opencv2/opencv.hpp>
using namespace cv;
#endif

#include "head.h"

void showMat(
#ifdef __cplusplus
const Mat &img
#else
IplImage *img
#endif
)
{
#ifdef __cplusplus
	Mat nimg;
	resize(img, nimg, Size(LCD_W, LCD_H), 0, 0, INTER_AREA);
	unsigned char *data = nimg.data;
	Address_set (0, 0, LCD_W - 1, LCD_H - 1);
#else
	IplImage *nimg = cvCreateImage(cvSize(LCD_W, LCD_H), img->depth, img->nChannels);
/*
	if (img->depth == IPL_DEPTH_8U )
		printf("%s\n", "IPL_DEPTH_8U ");
	if (img->depth == IPL_DEPTH_8S )
		printf("%s\n", "IPL_DEPTH_8S ");
	if (img->depth == IPL_DEPTH_16U )
		printf("%s\n", "IPL_DEPTH_16U ");
	if (img->depth == IPL_DEPTH_16S )
		printf("%s\n", "IPL_DEPTH_16S ");
	if (img->depth == IPL_DEPTH_32F )
		printf("%s\n", "IPL_DEPTH_32F ");
	if (img->depth == IPL_DEPTH_32S )
		printf("%s\n", "IPL_DEPTH_32S ");
	printf(" channels %d\n", img->nChannels);
	pause();
*/
	cvResize(img, nimg, CV_INTER_AREA);
	unsigned char *data = nimg->imageData;
#endif

	int  fd = open("data.dat", O_RDWR, 0666);
	write(fd, data, LCD_W * LCD_H);
	close(fd);
	pause();

	for (int i = 0; i < LCD_W * LCD_H; ++i) {
		unsigned short val = 0;
		//colormode rgb16 r:g:b 5:6:5
		val = (data[2] >> 3 << 11) | (data[0] >> 3) | (data[1] >> 2 << 5);
		LCD_WR_DATA8(val >> 8, val & 0xff);
		data += 3;
	}
#ifndef __cplusplus
	cvReleaseImage(&nimg);
#endif
}

void showimage(char *filename)
{
#ifdef __cplusplus
	Mat img = imread(filename);
#else
	IplImage *img = cvLoadImage(filename, 1);
#endif
	showMat(img);

#ifndef __cplusplus
	cvReleaseImage(&img);
#endif
}

int
main(int argc, char *argv[])
{
	wiringPiSetup();
	Lcd_Init();
/*
	LCD_Clear(WHITE);
	BACK_COLOR=BLACK;
	POINT_COLOR=WHITE; 
*/
	unsigned char i = 1;
	for(;i-- != 0;)
	{
		showimage(argv[1]);
/*
		LCD_Clear(BLACK);
		LCD_ShowString(0, i, "hello world gjq\n");
		i += 16;
*/
//		delay(1000);
    }

	return 0;
}
